package com.lyc.lojbackendquestionservice.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.lyc.lojbackendcommon.common.ErrorCode;
import com.lyc.lojbackendcommon.constant.CommonConstant;
import com.lyc.lojbackendcommon.exception.BusinessException;
import com.lyc.lojbackendcommon.exception.ThrowUtils;
import com.lyc.lojbackendcommon.utils.AlgorithmUtil;
import com.lyc.lojbackendcommon.utils.CopyUtil;
import com.lyc.lojbackendcommon.utils.CosineSimilarity;
import com.lyc.lojbackendcommon.utils.SqlUtils;
import com.lyc.lojbackendmodel.model.codesandbox.JudgeInfo;
import com.lyc.lojbackendmodel.model.dto.question.JudgeConfig;
import com.lyc.lojbackendmodel.model.dto.question.QuestionQueryRequest;
import com.lyc.lojbackendmodel.model.entity.Question;
import com.lyc.lojbackendmodel.model.entity.QuestionSubmit;
import com.lyc.lojbackendmodel.model.entity.User;
import com.lyc.lojbackendmodel.model.enums.QuestionSubmitResultStatusEnum;
import com.lyc.lojbackendmodel.model.vo.QuestionManageVO;
import com.lyc.lojbackendmodel.model.vo.QuestionSubmitVO;
import com.lyc.lojbackendmodel.model.vo.QuestionVO;
import com.lyc.lojbackendmodel.model.vo.UserVO;
import com.lyc.lojbackendquestionservice.mapper.QuestionMapper;
import com.lyc.lojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.lyc.lojbackendquestionservice.service.QuestionService;
import com.lyc.lojbackendquestionservice.service.QuestionSubmitService;
import com.lyc.lojbackendserviceclient.service.UserFeignClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.keyvalue.repository.KeyValueRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Linyichengzi
 * @description 针对表【question(题目)】的数据库操作Service实现
 * @createDate 2023-08-10 10:28:01
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
        implements QuestionService {

    @Resource
    private QuestionSubmitMapper questionSubmitMapper;
    
    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 题目推荐
     * @param questionId
     * @return
     */
    @Override
    public List<QuestionVO> getRecommend(Long questionId, HttpServletRequest request) {
        // 这里获取题目的所有信息，可以优化，只需要获取每个题目的标签和对应ID。
        List<Question> questionList = this.list();
        Question question = this.getById(questionId);
        String currentQuestionTags = question.getTags();
        Gson gson = new Gson();
        List<String> currentQuestionTagList = gson.fromJson(currentQuestionTags, new TypeToken<List<String>>() {
        }.getType());
        String curQuestionTagStr = currentQuestionTagList.toString();
        // 题目的下标 ==> 相似度大小。值（分数）从大道到小排序
//        TreeMap<Long, Double> indexDistanceMap = new TreeMap<>();
        // 使用 ConcurrentHashMap 保存相似度计算结果，避免重复计算
        ConcurrentHashMap<Long, Double> indexDistanceMap = new ConcurrentHashMap<>();
        for (Question ques : questionList) {
            Long quesId = ques.getId();
            String quesTags = ques.getTags();
            // 无标签或为本身
            if (Objects.equals(quesId, questionId) || StringUtils.isBlank(quesTags)) {
                continue;
            }
            List<String> questionTagList = gson.fromJson(quesTags, new TypeToken<List<String>>() {
            }.getType());
            String questionTagStr = questionTagList.toString();
            // 计算分数
            double  score= CosineSimilarity.getSimilarity(curQuestionTagStr,questionTagStr);
            System.out.println(score);
            indexDistanceMap.put(quesId, score);
        }

        // 并行处理题目相似度计算
/*        questionList.parallelStream().forEach(ques -> {
            Long quesId = ques.getId();
            String quesTags = ques.getTags();
            if (!Objects.equals(quesId, questionId) && StringUtils.isNotBlank(quesTags)) {
                List<String> questionTagList = gson.fromJson(quesTags, new TypeToken<List<String>>() {}.getType());
                String questionTagStr = questionTagList.toString();
                double score = CosineSimilarity.getSimilarity(curQuestionTagStr, questionTagStr);
                indexDistanceMap.put(quesId, score);
            }
        });*/
//        indexDistanceMap.forEach((key, value) -> {
//            System.out.println(key + " " + value);
//        });
        // 进行排序
        List<Long> sortedQuestionsByScore = getSortedQuestionsByScore(indexDistanceMap);
        List<Long> maxDistanceIndexList = sortedQuestionsByScore.stream().limit(5).collect(Collectors.toList());
        for(long index : maxDistanceIndexList) {
            System.out.println(index) ;
        }
        List<QuestionVO> questionVOList = maxDistanceIndexList.stream().map(id -> {
            Question ques = this.getById(id);
            return getQuestionVO(ques, request);
        }).collect(Collectors.toList());
        return questionVOList;
    }

    // 获取按相似度排序的题目ID列表
    private List<Long> getSortedQuestionsByScore(ConcurrentHashMap<Long, Double> indexDistanceMap) {
        return indexDistanceMap.entrySet().stream()
                .sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    /*public List<Long> getSortedQuestionsByScore(SortedMap<Long, Double> indexDistanceMap) {
        // Sort the indexDistanceMap by values in descending order
        List<Map.Entry<Long, Double>> sortedEntries = new LinkedList<>(indexDistanceMap.entrySet());
        Collections.sort(sortedEntries, new Comparator<Map.Entry<Long, Double>>() {
            @Override
            public int compare(Map.Entry<Long, Double> e1, Map.Entry<Long, Double> e2) {
                return e2.getValue().compareTo(e1.getValue()); // Descending order
            }
        });

        // Retrieve sorted quesIds
        List<Long> sortedQuestions = new ArrayList<>();
        for (Map.Entry<Long, Double> entry : sortedEntries) {
            sortedQuestions.add(entry.getKey());
        }

        return sortedQuestions;
    }*/

    /**
     * 校验题目是否合法
     *
     * @param question
     * @param add
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();
        String judgeCase = question.getJudgeCase();
        String judgeConfig = question.getJudgeConfig();
        Integer thumbNum = question.getThumbNum();
        Integer favourNum = question.getFavourNum();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
        //这里只是做安全的校验，判题用例和判题配置的校验可以详细一些
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题用例过长");
        }
        if (StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题配置过长");
        }
    }

    /**
     * 获取查询包装类（用户根据哪些字段去查询，根据前端传来的请求对象，得到mybatis框架支持的查询 QueryWrapper 类）
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
//        做题状态（0-全部，1-未开始，2-尝试过，3-已解答）
        Integer status = questionQueryRequest.getStatus();
        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        List<String> tags = questionQueryRequest.getTags();
        Long userId = questionQueryRequest.getUserId();
        // answer 和 content 常常不显示，不用查询
        String content = questionQueryRequest.getContent();
        String answer = questionQueryRequest.getAnswer();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        
        if(ObjectUtils.isNotEmpty(status) && status != 0) {
            User loginUser = userFeignClient.getLoginUser(request);
            Set<Long> passedIds;
            Set<Long> triedIds;
            switch (status){
                case 3:
                    passedIds = questionSubmitMapper.selectList(new LambdaQueryWrapper<QuestionSubmit>()
                            .select(QuestionSubmit::getQuestionId).eq(QuestionSubmit::getUserId, loginUser.getId())
                            .eq(QuestionSubmit::getResStatus, QuestionSubmitResultStatusEnum.SUCCEED.getValue()))
                            .stream()
                            .map(QuestionSubmit::getQuestionId)
                            .collect(Collectors.toSet());
                    if(passedIds.isEmpty()){
                        return null;
                    }
                    queryWrapper.in("id", passedIds);
                    break;
                case 2:
                    passedIds = questionSubmitMapper.selectList(new LambdaQueryWrapper<QuestionSubmit>()
                                    .select(QuestionSubmit::getQuestionId).eq(QuestionSubmit::getUserId, loginUser.getId())
                                    .eq(QuestionSubmit::getResStatus, QuestionSubmitResultStatusEnum.SUCCEED.getValue()))
                            .stream()
                            .map(QuestionSubmit::getQuestionId)
                            .collect(Collectors.toSet());
                    triedIds = questionSubmitMapper.selectList(new LambdaQueryWrapper<QuestionSubmit>()
                                    .select(QuestionSubmit::getQuestionId).eq(QuestionSubmit::getUserId, loginUser.getId())
                                    .ne(QuestionSubmit::getResStatus, QuestionSubmitResultStatusEnum.SUCCEED.getValue()))
                            .stream()
                            .map(QuestionSubmit::getQuestionId)
                            .collect(Collectors.toSet());
                    triedIds = (Set<Long>) CollUtil.subtract(triedIds, passedIds);
                    if(triedIds.isEmpty()){
                        return null;
                    }
                    queryWrapper.in("id", triedIds);
                    break;
                case 1:
                    triedIds =questionSubmitMapper.selectList(new LambdaQueryWrapper<QuestionSubmit>()
                            .select(QuestionSubmit::getQuestionId).eq(QuestionSubmit::getUserId, loginUser.getId()))
                            .stream()
                            .map(QuestionSubmit::getQuestionId)
                            .collect(Collectors.toSet());
                    if(!triedIds.isEmpty()){
                        queryWrapper.notIn("id", triedIds);
                    }
                    break;
            }
        }
        
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "content", answer);
        if (CollectionUtils.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_QUESTION_ASC),
                sortField);
        return queryWrapper;
    }
    
    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        User loginUser = userFeignClient.getLoginUser(request);
        Long loginUserId = loginUser.getId();
        QuestionSubmit submit = questionSubmitMapper.selectOne(new QueryWrapper<QuestionSubmit>()
                        .lambda()
                        .eq(QuestionSubmit::getQuestionId, question.getId())
                        .eq(QuestionSubmit::getUserId, loginUserId)
                        .orderByDesc(QuestionSubmit::getResStatus)
                        .last("LIMIT 1"));

        if(submit == null){
            questionVO.setStatus(1);
        } else if(submit.getResStatus().equals(QuestionSubmitResultStatusEnum.SUCCEED.getValue())) {
            questionVO.setStatus(3);
        } else if(submit.getResStatus().equals(QuestionSubmitResultStatusEnum.FAILED.getValue())){
            questionVO.setStatus(2);
        } else {
            questionVO.setStatus(1);
        }
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userFeignClient.getById(userId);
        }
        UserVO userVO = userFeignClient.getUserVO(user);
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollectionUtils.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userFeignClient.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userId = question.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUserVO(userFeignClient.getUserVO(user));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }
    

    /**
     * 获取单个题目管理信息封装类
     *
     * @param question
     * @param loginUser
     * @return
     */
    @Override
    public QuestionManageVO getQuestionManagerVO(Question question, User loginUser) {
        //脱敏，仅本人和管理员能看见自己（提交userId 和登陆用户id不同）提交的代码
        QuestionManageVO questionManageVO = new QuestionManageVO();
        BeanUtils.copyProperties(question, questionManageVO);
        Long userId = question.getUserId();
        User user = userFeignClient.getById(userId);
        String userName = user.getUserName();
        questionManageVO.setUserName(userName);
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        questionManageVO.setMemoryLimit(judgeConfig.getMemoryLimit());
        questionManageVO.setTimeLimit(judgeConfig.getTimeLimit());
        questionManageVO.setStackLimit(judgeConfig.getStackLimit());
        return questionManageVO;
    }
    
    /*@Override
    public Page<QuestionManageVO> listManageQuestionByPage(Page<Question> questionPage, QueryWrapper<Question> queryWrapper) {
        this.page(questionPage, queryWrapper);
        Page<QuestionManageVO> questionManageVoPage = new Page<>();
        BeanUtils.copyProperties(questionPage, questionManageVoPage, "records");
        List<Long> userIdList = questionPage.getRecords().stream().map(Question::getUserId).collect(Collectors.toList());
        List<User> userList = userFeignClient.list(
                Wrappers.lambdaQuery(User.class).select(User::getUserName, User::getId).in(User::getId, userIdList)
        );
        Map<Long, List<User>> userIdToName = userList.stream().collect(Collectors.groupingBy(User::getId));
        questionManageVoPage.setRecords(
                questionPage.getRecords().stream().map(question -> {
                    QuestionManageVO questionManageVO = CopyUtil.copy(question, QuestionManageVO.class);
                    if (userIdToName.containsKey(question.getUserId())) {
                        questionManageVO.setUserName(userIdToName.get(question.getUserId()).get(0).getUserName());
                    }
                    JudgeConfig judgeConfig = JSONUtil.toBean(question.getJudgeConfig(), JudgeConfig.class);
                    questionManageVO.setTimeLimit(judgeConfig.getTimeLimit());
                    questionManageVO.setMemoryLimit(judgeConfig.getMemoryLimit());
                    questionManageVO.setStackLimit(judgeConfig.getStackLimit());
                    return questionManageVO;
                }).collect(Collectors.toList())
        );
        return questionManageVoPage;
    }*/

    @Override
    public Page<QuestionManageVO> getQuestionManageVOPage(Page<Question> questionPage, User loginUser) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionManageVO> questionManageVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollectionUtils.isEmpty(questionList)) {
            return questionManageVOPage;
        }
        // 填充信息
        List<QuestionManageVO> questionManageVOList = questionList.stream()
                .map(question -> getQuestionManagerVO(question, loginUser))
                .collect(Collectors.toList());
        questionManageVOPage.setRecords(questionManageVOList);
        return questionManageVOPage;
    }
    
}




